<template>
    <div>
        <canvas id="canvas"></canvas>
        <el-button type="primary"  size="mini"  @click="addImg">添加</el-button>
        <el-button type="primary"   size="mini"  @click="btnClick">新增自定义</el-button>
        <el-button type="primary"  size="mini"   @click="canvasTOJSON">转JSON</el-button>
        <el-button type="primary"    size="mini"  :disabled="!enable" @click="loadFromJSON">转canvas预览</el-button>
        <div v-show="showenable">
            <!--<div style="width:500px;height:300px;border:1px solid black;overflow:hidden" @mousedown.prevent.stop="moveImg" @mousewheel.prevent.stop="mouseWheel">拖拽部分获取画布焦点有问题-->
            <div style="width:500px;height:300px;border:1px solid black;overflow:hidden" @mousedown.prevent.stop="moveImg">
                <canvas id="loadCanvas" :style="imgStyle"></canvas>
            </div>
            <div @mousedown.prevent="showArea" style="transform:scale(0.1);transform-origin:0 0;position:relative">
                <div id="selectArea" :style="style"></div>
                <img style="position:absolute;left:0;top:0" src='static/images/image/bgS.png' />
            </div>
            <el-dialog title="坐席" :visible.sync="dialogFormVisible">
                <el-form :model="form">
                    <el-form-item label="坐席id">
                        <el-input v-model="form.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="活动区域">
                        <el-select v-model="form.region" placeholder="请选择活动区域">
                            <el-option label="区域一" value="shanghai"></el-option>
                            <el-option label="区域二" value="beijing"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button  size="mini" @click="dialogFormVisible = false">确定</el-button>
                    <el-button   size="mini"  type="primary" @click="canvasRemove">删除</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>
<script>
import { fabric } from 'fabric';

export default {
    name: 'EditMap',
    created() {
        this.draw();
    },
    data() {
        return {
            styleData: {
                'width': 500,
                'height': 300,
                'left': 0,
                'top': 0,
                'scale': 0.1,
                'imgScale': 1
            },
            enable: false,
            showenable: false,
            // 视图拖动灵敏度
            sensitivity: 0.1,
            image: '',
            canvas: '',
            selectval: '',
            ctx: '',
            canvasJSON: '',
            dialogFormVisible: false,
            loadCanvas: '',
            mapWidth: 0,
            mapHeight: 0,
            form: {
                name: '',
                region: ''
            },
            id: 1 // 页面元素标记唯一id
        }
    },
    computed: {
        style() {
            return {
                'width': this.styleData.width + 'px',
                'height': this.styleData.height + 'px',
                'border': '2px solid red',
                'position': 'relative',
                'backaground':'static/images/image/bgS.png',
                'left': this.styleData.left + 'px',
                'top': this.styleData.top + 'px',
                'z-index': 10,
                'wheelClientX': 0,
                'wheelClientY': 0
            }
        },
        imgStyle() {
            return {
                'position': 'relative',
                'left': -this.styleData.left + 'px',
                'top': -this.styleData.top + 'px',
                'transform': 'scale(' + this.styleData.imgScale + ')',
                'transform-origin': this.styleData.wheelClientX + 'px ' + this.styleData.wheelClientY + 'px'
            }
        }
    },
    methods: {
        // 点击图片位置跳转显示区域
        showArea(event) {
            // 鼠标点击坐标
            let offsetX = event.offsetX * this.styleData.scale;
            let offsetY = event.offsetY * this.styleData.scale;
            // 矩形框中心点坐标
            let middleX = (this.styleData.width / 2 + this.styleData.left) * this.styleData.scale;
            let middleY = (this.styleData.height / 2 + this.styleData.top) * this.styleData.scale;
            // 移动距离
            let moveX = offsetX - middleX;
            let moveY = offsetY - middleY;
            console.log(moveX, moveY)
            // 定位
            this.styleData.left = (moveX + this.styleData.left * this.styleData.scale) / this.styleData.scale;
            this.styleData.top = (moveY + this.styleData.top * this.styleData.scale) / this.styleData.scale;
        },
        //拖拽放大显示区域图片
        moveImg(event) {
            // 点击坐标
            let clientX = event.clientX;
            let clientY = event.clientY;
            // 图片宽高
            let imgWidth = document.getElementById("loadCanvas").clientWidth;
            let imgHeight = document.getElementById("loadCanvas").clientHeight;
            // console.log(imgWidth, imgHeight, 'ttt')
            // 定义移动方法
            let move = moveEvent => {
                console.log(moveEvent)
                // 移动当前位置坐标
                let currX = moveEvent.clientX;
                let currY = moveEvent.clientY;
                // 移动距离
                let moveX = (clientX - currX);
                let moveY = (clientY - currY);
                console.log(this.styleData.left)
                if (this.styleData.left >= 0 && this.styleData.left <= (imgWidth - this.styleData.width)) {
                    this.styleData.left += moveX * this.sensitivity;
                } else {
                    this.styleData.left = 0
                }
                if (this.styleData.top >= 0 && this.styleData.top <= (imgHeight - this.styleData.height)) {
                    this.styleData.top += moveY * this.sensitivity;
                } else {
                    this.styleData.top = 0
                }
            };
            let up = () => {
                document.removeEventListener('mousemove', move);
                document.removeEventListener('mouseup', up);
            }
            document.addEventListener('mousemove', move);
            document.addEventListener('mouseup', up)
        },

        // 滚轮缩放
        mouseWheel(event) {
            console.log(event.clientX, event.clientY, event.wheelDelta, this.styleData.left, this.styleData.top)
            this.styleData.wheelClientX = event.clientX + this.styleData.left;
            this.styleData.wheelClientY = event.clientY + this.styleData.top;
            if (event.wheelDelta > 0) {
                this.styleData.imgScale < 2 ? this.styleData.imgScale += 0.1 : this.styleData.imgScale = 2
            } else {
                this.styleData.imgScale > 0.5 ? this.styleData.imgScale -= 0.1 : this.styleData.imgScale = 0.5
            }
        },
        // 绘制地图
        draw() {
            let that = this;
            // 获取地图图片宽高
            fabric.Image.fromURL('static/images/image/bgS.png', function(img) {
                // 定义canvas
                that.mapWidth = img.width;
                that.mapHeight = img.height;
                that.canvas = new fabric.Canvas('canvas', {
                    width: that.mapWidth,
                    height: that.mapHeight
                });
                // 地图设为canvas背景图
                that.canvas.setBackgroundImage('static/images/image/bgS.png',that.canvas.renderAll.bind(that.canvas));
                // 背景地图id为0
                that.canvas.set({ id: 0 })
            });
        },
        // 添加坐席
        addImg() {
            let that = this;
            // 坐席底色
            let rect = new fabric.Rect({
                width: 70,
                height: 70,
                fill: '#1296db'
            });
            fabric.Image.fromURL('static/images/icons/icon/staff.png', function(img) {
                console.log(that.canvas, 'before')
                img.set({ id: that.id++ });
                console.log(img, 'img')
                // let group = new fabric.Group([rect,img],{
                //     selectable: true
                // });                
                that.canvas.add(img);
                that.canvas.renderAll();
                console.log(that.canvas, 'after')
            });
        },
        //初始化Group图标方法
        btnClick() {
            let that = this;
            fabric.Image.fromURL('static/images/icons/icon/staff.png', function(img) {
                var img1 = img.scale(0.1).set({ left: 5 });
                fabric.Image.fromURL('static/images/icons/icon/logout.png',function(img) {
                    var img2 = img.scale(0.1).set({ left: 25 });
                    var rect = new fabric.Rect({
                        fill: 'green',
                        width: 50,
                        height: 50,
                        rx: 10,
                        ry: 10,
                    });
                    var num = new fabric.Text('A10423', {//绘制文本
                        fontSize: 5,
                        originX: 'center',
                        originY: 'center',
                        top: 30,
                        left: 15
                    })
                    var name = new fabric.Text('高圆圆', {//绘制文本
                        fontSize: 5,
                        originX: 'center',
                        originY: 'center',
                        top: 42,
                        left: 15
                    })
                    var group = new fabric.Group([rect, num, name, img1, img2],
                        { lockScalingX: true, lockScalingY: true });
                    group.set({ id: that.id++ });
                    that.canvas.add(group);
                    console.log(group);
                    console.log(that.canvas, 'after');
                });
            });
        },
        // canvas转JSON
        canvasTOJSON() {
            this.canvasJSON = this.canvas.toJSON(['id']);
            console.log(this.canvasJSON)
            this.enable = true;
        },
        //编辑移除对象
        canvasRemove() {
            this.dialogFormVisible = false;
            console.log(this.selectval);
            this.loadCanvas.remove(this.selectval);
            this.loadCanvas.renderAll();
            console.log("this.localCanvas,",this.loadCanvas);
        },
        // JSON转canvas
        loadFromJSON() {
            if (!this.loadCanvas) {
                this.loadCanvas = new fabric.Canvas('loadCanvas', {
                    width: this.mapWidth,
                    height: this.mapHeight
                });
            }
            let that = this
            this.loadCanvas.loadFromJSON(this.canvasJSON, function() {
                console.log(that.loadCanvas._objects, 'eeeee')
                that.loadCanvas._objects.map(function(val) {
                    // 去除边框
                    val['hasBorders'] = false;
                    // 禁止缩放
                    val['hasControls'] = false;
                    // 禁止移动
                    val['selectable'] = false;
                    val.on('mousedown', function() {
                        console.log('mousedown', val.id);
                        that.form.name = val.id;
                        that.selectval = val;
                        that.dialogFormVisible = true;
                    })
                    return val;
                })
                // // 去除边框
                // that.loadCanvas.item(0)['hasBorders'] = false;
                // // 禁止缩放
                // that.loadCanvas.item(0)['hasControls'] = false;
                // // 禁止移动
                // that.loadCanvas.item(0)['evented'] = false;
            });
            this.loadCanvas.renderAll()
            this.showenable = true;
            //添加点击页面添加元素获取id事件
            // that.loadCanvas.on('object:selected', function(e) {
            //     console.log(e,'event')
            //     if(e.target) {
            //         alert(e.target.id);
            //     }
            // })            
            console.log(this.loadCanvas)
        }
    }
}
</script>
<style scoped>

</style>